package org.openclinic.exception;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;


public abstract class AbstractExceptionHandler {

	@Autowired
	private ReloadableResourceBundleMessageSource messageSource;
	
	@ExceptionHandler(DomainException.class)
	@ResponseStatus(value = HttpStatus.CONFLICT)
	@ResponseBody
	public List<ErrorMessage> handleDomainException(DomainException ex, HttpServletResponse response) {
		List<ErrorMessage> errors = new ArrayList<ErrorMessage>();
		
		for (ObjectError e : ex.getErrors()) {
			FieldError error = (FieldError) e;
			errors.add(new ErrorMessage(error.getField(), messageSource.getMessage(error, Locale.getDefault())));
		}
		
		return errors;
	}
	
}
